/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.crane.webtemplate;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.crane.webtemplate.dao.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author CraneLeeon
 */
public class HibernateSessionFilter implements Filter {

    private static final Log log = LogFactory.getLog(HibernateSessionFilter.class);
    // The filter configuration object we are associated with.  If
    // this value is null, this filter instance is not currently
    // configured. 
    private FilterConfig filterConfig = null;

    public HibernateSessionFilter() {
    }

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
//        log.trace("===> opening session for request [" + request.hashCode() + "]");
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        try {
            chain.doFilter(request, response);
            Transaction tc = session.getTransaction();
            if (tc != null && tc.isActive() && (!tc.wasCommitted() || !tc.wasRolledBack())) {
                tc.commit();
            }
        } catch (Exception ex) {
            if (session != null && session.isOpen()) {
                Transaction tc = session.getTransaction();
                if (tc != null && tc.isActive() && (!tc.wasRolledBack() || !tc.wasCommitted())) {
                    tc.rollback();
                }
            }
        } finally {
//            log.trace("===> cleaning-up session for request [" + request.hashCode() + "]");
            try {
                if (session != null && session.isOpen()) {
                    session.close();
                }
            } catch (Throwable t) {
                log.warn("was unable to properly close session for request [" + request.hashCode() + "]");
            }
        }
    }

    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter 
     */
    public void destroy() {
    }

    /**
     * Init method for this filter 
     */
    public void init(FilterConfig filterConfig) {
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        if (filterConfig == null) {
            return ("HibernateSessionFilter()");
        }
        StringBuffer sb = new StringBuffer("HibernateSessionFilter(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());
    }
}
